import { PointTypeEnum } from '@/constant.enum';

import { PointsHistory } from '../points-history/entities/points-history.entity';
import { Points } from './entities/points.entity';

export function countPoints(list: Pick<PointsHistory, 'points' | 'type'>[]) {
  const data = new Points();
  data.historyPoints = 0;
  data.usedPoints = 0;
  data.points = 0;

  list.forEach((v) => {
    if (v.points > 0) {
      // 历史总积分: 增加的积分
      data.historyPoints =
        Math.floor((v.points + data.historyPoints) * 100) / 100;
    } else {
      // 已使用积分：不算增加的积分
      data.usedPoints =
        Math.floor((Math.abs(v.points) + data.usedPoints) * 100) / 100;
    }

    if (v.type === PointTypeEnum['退款']) {
      data.historyPoints -= Math.abs(v.points);
      data.usedPoints -= Math.abs(v.points);
    }

    // 可用积分：历史总积分 - 已使用积分
    data.points =
      Math.floor((data.historyPoints - data.usedPoints) * 100) / 100;
  });

  return data;
}
